<template>
  <div
    v-loading="
      processFlg || deviceFlg || clampFlg || personnelFlg || saveLoading
    "
    element-loading-text="数据加载中..."
  >
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item>
        <span>产线名称：</span>
        <el-input
          v-model="form.lineName"
          placeholder="请输入"
          style="width: 200px; margin-right: 5px"
          label="产线名称"
          disabled
        ></el-input>
        <span style="margin-left: 20px">车间：</span>
        <el-select
          v-model="workshopId"
          placeholder="请选择车间"
          filterable
          clearable
          style="width: 200px; margin-right: 5px"
          label="车间"
          disabled
        >
          <el-option
            v-for="item in workshopList"
            :key="item.id"
            :label="item.workshopName"
            :value="item.id"
            @click.native="workshopChange(item)"
          >
          </el-option>
        </el-select>
        <span style="margin-left: 20px">产线类型：</span>
        <el-select
          v-model="form.lineType"
          placeholder="请选择产线类型"
          filterable
          clearable
          style="width: 200px; margin-right: 5px"
          label="产线类型"
          disabled
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.productCategory"
            :value="item.productCategory"
            @click.native="categoryChange(item)"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          style="margin-left: 100px"
          @click="downloadTemplate"
          >模版下载</el-button
        >
        <el-button type="primary" @click="importExcel">Excel快速导入</el-button>
        <el-button type="primary" @click="save">保存</el-button>
        <!--        <el-button type="primary" @click="handleClose">取消</el-button>-->
        <el-button type="button" class="my-cancel-button" @click="handleClose"
          >取消</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addRow">添加行</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" border height="620">
      <el-table-column type="index" label="序号"></el-table-column>

      <el-table-column label="工序名称">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.processName"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="(item, index) in processList"
              :key="index"
              :label="item.processName"
              :value="item.processName"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="工位">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.workPositionId"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="(item, index) in workPositionList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="设备">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.equipment"
            placeholder="请选择"
            @focus="scope.row.deviceShowOption = true"
            @blur="scope.row.deviceShowOption = false"
            style="width: 250px"
            multiple
            filterable
            clearable
          >
            <el-option
              v-if="scope.row.deviceShowOption"
              v-for="(item, index) in deviceList"
              :key="index"
              :label="`${item.deviceName} (${item.deviceSn})`"
              :value="item.deviceSn"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="夹具">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.fixture"
            @focus="scope.row.fixtureShowOption = true"
            @blur="scope.row.fixtureShowOption = false"
            placeholder="请选择"
            multiple
            style="width: 250px"
            filterable
            clearable
          >
            <el-option
              v-if="scope.row.fixtureShowOption"
              v-for="(item, index) in clampList"
              :key="index"
              :label="`${item.deviceName} (${item.deviceSn})`"
              :value="item.deviceSn"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="人员">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.personnel"
            @focus="scope.row.personnelShowOption = true"
            @blur="scope.row.personnelShowOption = false"
            placeholder="请选择"
            multiple
            style="width: 250px"
            filterable
            clearable
          >
            <el-option
              v-for="item in personCredentialList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="moveUp(scope.$index)">上移</el-button>
          <el-button size="mini" @click="moveDown(scope.$index)"
            >下移</el-button
          >
          <el-button size="mini" type="danger" @click="deleteRow(scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// import XLSX from 'xlsx'
import { downBlobFile } from "@/util";

const XLSX = require("xlsx");
import { getObj } from "@/api/pfoc/factorysettings"; //获取当前工厂信息
import { getDevice } from "@/api/hengdong/pfocinterface"; //获取设备相关
import { getWorkshopList } from "@/api/pfoc/workshop"; //获取全部车间
import { getPersonCredentialList } from "@/api/workorder/personcredentialmanage";
import { getCategory } from "@/api/workorder/hdviewapiitem"; //获取品类
import { getPfocProcessList } from "@/api/pfoc/pfocprocess";
import { updateProductLine, getById } from "@/api/pfoc/realityproductlinemain";
import { getWorkPositionList } from "@/api/common.js";

export default {
  props: {
    lineId: {
      //产线ID
      type: String,
    },
  },
  data() {
    return {
      form: {
        lineName: "",
        workshop: "",
        lineType: "",
      },
      tableData: [],
      workshopList: [],
      workPositionList: [],
      workshopId: null,
      processList: [],
      categoryList: [],
      category: null,
      deviceList: [],
      clampList: [],
      toolList: [],
      personCredentialList: [],
      organizationId: null,
      organizationName: null,
      processFlg: true,
      deviceFlg: true,
      clampFlg: true,
      personnelFlg: true,
      saveLoading: false,
      loading: null, // 用于存储loading实例
    };
  },
  created() {
    //获取所有人员数据
    this.getPersonCredentialListData();
    this.getById();
    //获取当前工厂信息
    this.getFactoryInfo();
    //获取车间集合
    this.getWorkshopListData();

    // 获取产线类型数据
    this.getCategoryData();
    // 获取工序名称数据
    this.getProcessListData();
    this.getWorkPositionLists();
  },
  mounted() {
    this.addDefaultRows();
  },
  methods: {
    async getWorkPositionLists() {
      let data = { parentId: "1909860013956497410" };
      const res = await getWorkPositionList(data);
      this.workPositionList = [
        ...res.data.data.map((item) => {
          return {
            value: item.id,
            label: item.workPositionName,
          };
        }),
      ];
    },
    addDefaultRows() {
      for (let i = 0; i < 10; i++) {
        this.tableData.push({
          processName: "",
          equipment: [], // 修改为数组类型，支持多选
          deviceShowOption: false,
          fixture: [], // 修改为数组类型
          fixtureShowOption: false,
          personnel: [], // 修改为数组类型，支持多选
          personnelShowOption: false,
        });
      }
    },

    getById() {
      const data = {
        id: this.lineId,
      };

      getById(data).then((response) => {
        if (response.data.code === 0) {
          const resData = response.data.data;
          // 回显表单数据
          this.form.lineName = resData.realityLineName;
          this.workshopId = resData.workshopId;
          this.form.lineType = resData.lineType;

          // 回显表格数据
          this.tableData = resData.list.map((item) => {
            const equipment = item.device ? item.device.split(",") : [];
            const fixture = item.clamp ? item.clamp.split(",") : [];


            const personnel = item.jobNo ? item.jobNo.split(",") : [];

            return {
              processName: item.processName,
              workPositionId: item.workPositionId,
              equipment,
              fixture,
              personnel,
              fixtureShowOption: fixture.length > 0,
              personnelShowOption: false,
              deviceShowOption: equipment.length > 0,
            };
          });
          // 延迟 1 秒执行
          setTimeout(() => {
            this.tableData.forEach((item) => {
              item.fixtureShowOption = false;
              item.personnelShowOption = false;
              item.deviceShowOption = false;
            });
          }, 2000);
        }
      });
    },

    /**获取工厂信息*/
    getFactoryInfo() {
      const factoryId = 1;
      getObj(factoryId).then((response) => {
        this.organizationId = response.data.data.menuId; //组织ID
        this.organizationName = response.data.data.organizationName; //组织名称
        //获取工厂设备集合
        this.getFactoryDeviceList();
      });
    },
    /**获取工厂设备集合*/
    getFactoryDeviceList() {
      var obj = {
        position: this.organizationName, //设置组织查询条件
      };
      getDevice(obj).then((response) => {
        this.deviceList = response.data.data; //设备集合
        for (var i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i].deviceClass === "20") {
            //组织下工具夹具筛选
            this.clampList.push(this.deviceList[i]); //夹具集合
            this.toolList.push(this.deviceList[i]); //工具集合
          }
        }
        this.deviceFlg = false;
        this.clampFlg = false;
      });
    },
    /**获取车间集合*/
    getWorkshopListData() {
      getWorkshopList().then((response) => {
        this.workshopList = response.data.data;
      });
    },
    /**车间选择*/
    workshopChange(row) {
      this.workshopName = row.workshopName; //车间名称

    },
    //获取所有人员数据
    getPersonCredentialListData() {
      getPersonCredentialList().then((response) => {
        this.personCredentialList = response.data.data.map((item) => {
          return {
            value: item.jobNo,
            label: item.personName,
          };
        });
        this.personnelFlg = false;
      });
    },
    // 获取产线类型数据
    async getCategoryData() {
      getCategory().then((response) => {
        this.categoryList = response.data.data;
      });
    },
    // 获取工序名称数据
    async getProcessListData() {
      getPfocProcessList().then((response) => {
        this.processList = response.data.data;
        this.processFlg = false;
      });
    },
    downloadTemplate() {
      downBlobFile(
        "/pfoc/craftproduct/local/file/产线建模导入.xlsx",
        "",
        "产线建模导入.xlsx"
      );
    },
    /**产线类型选择 */
    categoryChange(row) {
      // this.category = row.
      // 这里可以添加选择产线类型后的逻辑
    },
    addRow() {
      this.tableData.push({
        processName: "",
        equipment: [], // 修改为数组类型，支持多选
        deviceShowOption: false,
        fixture: [], // 修改为数组类型
        fixtureShowOption: false,
        personnel: [], // 修改为数组类型，支持多选
        personnelShowOption: false,
      });
    },
    importExcel() {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".xlsx, .xls";
      input.onchange = (e) => {
        const file = e.target.files[0];
        if (file) {
          // 显示加载提示
          this.loading = this.$loading({
            lock: true,
            text: "正在解析数据，请稍候...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          const reader = new FileReader();
          reader.onload = (event) => {
            const data = event.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            const newTableData = [];
            const unimportedInfo = [];

            jsonData.forEach((item) => {
              const fixtureCodes = (item["夹具编码"] || "")
                .split(",")
                .map((s) => s.trim());
              const personnelCodes = String(item["员工号"] || "")
                .split(",")
                .map((s) => s.trim());
              const processName = item["工序名称"] || "";
              const workPositionName = item["工位"] || "";
              const equipmentCodes = (item["设备编码"] || "")
                .split(",")
                .map((s) => s.trim()); // 处理多选设备编码

              const unmatchedFixtures = [];
              const unmatchedPersonnel = [];
              let unmatchedProcess = null;
              let unmatchedworkPosition = null;
              let unmatchedEquipment = []; // 修改为数组类型，支持多个未匹配设备

              const validFixtureCodes = fixtureCodes.filter((code) => {
                const clamp = this.clampList.find((c) => c.deviceSn === code);
                if (!clamp) {
                  unmatchedFixtures.push(code);
                  return false;
                }
                return true;
              });

              const validPersonnelCodes = personnelCodes.filter((code) => {
                const person = this.personCredentialList.find(
                  (p) => p.jobNo === code
                );
                if (!person) {
                  unmatchedPersonnel.push(code);
                  return false;
                }
                return true;
              });

              const process = this.processList.find(
                (p) => p.processName === processName
              );
              if (!process) {
                unmatchedProcess = processName;
              }

              const workPosition = this.workPositionList.find(
                (p) => p.label === workPositionName
              );
              if (!workPosition) {
                unmatchedworkPosition = workPositionName;
              }

              const validEquipmentCodes = equipmentCodes.filter((code) => {
                const equipment = this.deviceList.find(
                  (d) => d.deviceSn === code
                );
                if (!equipment) {
                  unmatchedEquipment.push(code);
                  return false;
                }
                return true;
              });

              newTableData.push({
                processName: process ? processName : "",
                workPositionName: workPosition ? workPositionName : "",
                workPositionId: workPosition ? workPosition.value : "",
                equipment: validEquipmentCodes, // 存储多选设备编码
                fixture: validFixtureCodes,
                personnel: validPersonnelCodes,
                fixtureShowOption: true,
                personnelShowOption: true,
                deviceShowOption: true,
              });

              if (unmatchedProcess) {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：工序名称 [${unmatchedProcess}] 未匹配到`
                );
              }
              if (unmatchedworkPosition) {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：工位名称 [${unmatchedworkPosition}] 未匹配到`
                );
              }
              if (unmatchedEquipment.length > 0) {
                unmatchedEquipment.forEach((code) => {
                  unimportedInfo.push(
                    `第 ${item["序号"]} 行：设备编码 [${code}] 未匹配到`
                  );
                });
              }
              unmatchedFixtures.forEach((code) => {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：夹具编码 [${code}] 未匹配到`
                );
              });
              unmatchedPersonnel.forEach((code) => {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：员工号 [${code}] 未匹配到`
                );
              });
            });

            this.tableData = newTableData;
            this.$nextTick(() => {
              this.tableData.forEach((item) => {
                item.fixtureShowOption = false;
                item.personnelShowOption = false;
                item.deviceShowOption = false;
              });
            });
            if (unimportedInfo.length > 0) {
              const unimportedDataStr = unimportedInfo.join("<br>");
              this.$confirm(
                `以下数据部分字段未导入：<br>${unimportedDataStr}`,
                "提示",
                {
                  confirmButtonText: "确定",
                  customClass: "custom-confirm-dialog", // 添加自定义类名
                  type: "warning",
                  dangerouslyUseHTMLString: true,
                }
              )
                .then(() => {
                  // 点击确认后关闭弹框
                })
                .catch(() => {
                  // 取消操作，不做任何处理
                });
            }
            // 数据解析完成，关闭加载提示
            this.loading.close();
          };
          reader.readAsBinaryString(file);
        }
      };
      input.click();
    },
    save() {
      // 验证产线名称、车间、产线类型是否为空
      if (!this.form.lineName) {
        this.$message.error("产线名称不能为空");
        return;
      }
      if (!this.workshopId) {
        this.$message.error("车间不能为空");
        return;
      }
      if (!this.form.lineType) {
        this.$message.error("产线类型不能为空");
        return;
      }

      // 验证列表是否包含一条工序数据
      if (
        this.tableData.length === 0 ||
        this.tableData.every((row) => !row.processName)
      ) {
        this.$message.error("列表必须包含一条工序数据");
        return;
      }

      // 验证列表每一行如果有一个填写了就必须把剩余的都填写完成
      for (let i = 0; i < this.tableData.length; i++) {
        const row = this.tableData[i];
        const hasAnyValue =
          row.processName ||
          row.equipment.length > 0 ||
          row.fixture.length > 0 ||
          row.personnel.length > 0;
        if (hasAnyValue) {
          if (!row.processName) {
            this.$message.error(`第 ${i + 1} 行工序名称未填写`);
            return;
          }
          // if (row.equipment.length === 0) {
          //   this.$message.error(`第 ${i + 1} 行设备未填写`)
          //   return
          // }
          // if (row.fixture.length === 0) {
          //   this.$message.error(`第 ${i + 1} 行夹具未填写`)
          //   return
          // }
          // if (row.personnel.length === 0) {
          //   this.$message.error(`第 ${i + 1} 行人员未填写`)
          //   return
          // }
        }
      }

      const dataToSave = {
        realityLineName: this.form.lineName,
        workshopId: this.workshopId, // 使用选中的车间ID
        workshopName: "",
        lineType: this.form.lineType,
        id: this.lineId,
        deviceSnStr: "",
        list: [],
      };

      // 根据ID获取车间名称
      const workshop = this.workshopList.find((w) => w.id === this.workshopId);
      if (workshop) {
        dataToSave.workshopName = workshop.workshopName;
      }
      let deviceSnStr = "";
      // 处理 list 数据，剔除空数据行
      this.tableData.forEach((row, index) => {
        const hasData =
          row.processName ||
          row.equipment.length > 0 ||
          row.fixture.length > 0 ||
          row.personnel.length > 0;

        if (hasData) {
          const item = {
            processId: "", // 假设这里没有提供工序ID的获取逻辑，先设为空字符串
            processName: row.processName,
            workPositionName: this.workPositionList.find(
              (d) => d.value == row.workPositionId
            ).label,
            workPositionId: row.workPositionId,
            nodeId: index + 1, // 假设这里没有提供排序的获取逻辑，先设为空字符串
            device: row.equipment.join(","), // 拼接多选设备编码
            deviceNames: "",
            clamp: "",
            clampNames: "",
            workshopSection: "",
            jobNo: "",
          };

          // 根据设备编码获取设备名称
          const devices = row.equipment.map((code) =>
            this.deviceList.find((d) => d.deviceSn === code)
          );
          item.deviceNames = devices
            .filter(Boolean)
            .map((d) => d.deviceName)
            .join(",");
          deviceSnStr = deviceSnStr + row.equipment.join(",") + ",";

          // 获取选中工序id
          const process = this.processList.find(
            (d) => d.processName === row.processName
          );
          if (process) {
            item.processId = process.id;
            // item.workshopSection = process.workshopSection;
          }
          console.log(this.clampList);
          // 处理夹具编码和名称
          item.clamp = row.fixture
            .map((f) => {
              const parts = f.match(/\((.*)\)/);
              return parts ? parts[1] : f;
            })
            .join(",");
          // 循环 clamp 去 clampList 匹配 deviceName 并拼接
          const clampNamesArray = [];
          row.fixture.forEach((fixture) => {
            const parts = fixture.match(/\((.*)\)/);
            const fixtureSn = parts ? parts[1] : fixture;
            const foundClamp = this.clampList.find(
              (c) => c.deviceSn === fixtureSn
            );
            if (foundClamp) {
              clampNamesArray.push(foundClamp.deviceName);
            }
          });
          item.clampNames = clampNamesArray.join(",");
          // 处理人员数据
          item.jobNo = row.personnel.join(",");
          dataToSave.list.push(item);
        }
      });
      //判断deviceSnStr不为空截取最后一个逗号
      if (deviceSnStr.length > 0) {
        deviceSnStr = deviceSnStr.substring(0, deviceSnStr.length - 1);
      }
      dataToSave.deviceSnStr = deviceSnStr;
      this.saveLoading = true;

      updateProductLine(dataToSave)
        .then((response) => {
          if (response.data.code === 0) {
            this.$message.success("保存成功");
            this.handleClose();
          } else {
            this.$message.error("保存失败：" + response.data.message);
          }
        })
        .catch((error) => {
          this.saveLoading = false;
          console.error("保存请求出错", error);
          this.$message.error("保存过程中出现错误，请检查网络或重试");
        });
    },
    moveUp(index) {
      // 新增行空值不能上移
      const row = this.tableData[index];
      if (
        index > 0 &&
        (row.processName ||
          row.equipment ||
          row.fixture.length > 0 ||
          row.personnel.length > 0)
      ) {
        const temp = this.tableData[index];
        this.tableData.splice(index, 1);
        this.tableData.splice(index - 1, 0, temp);
      }
    },
    moveDown(index) {
      if (index < this.tableData.length - 1) {
        const currentRow = this.tableData[index];
        const nextRow = this.tableData[index + 1];
        const currentRowHasData =
          currentRow.processName ||
          currentRow.equipment ||
          currentRow.fixture.length > 0 ||
          currentRow.personnel.length > 0;
        const nextRowHasData =
          nextRow.processName ||
          nextRow.equipment ||
          nextRow.fixture.length > 0 ||
          nextRow.personnel.length > 0;
        if (currentRowHasData && nextRowHasData) {
          const temp = this.tableData[index];
          this.tableData.splice(index, 1);
          this.tableData.splice(index + 1, 0, temp);
        }
      }
    },
    deleteRow(index) {
      this.tableData.splice(index, 1);
    },
    handleClose() {
      this.saveLoading = false;
      this.$emit("closeEdit"); //关闭新增页面
    },
  },
};
</script>

<style scoped>
::v-deep .my-import-button {
  position: relative;
}

::v-deep .my-cancel-button {
  background-color: white;
  color: black;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

/* 为弹窗添加自定义样式 */
.custom-confirm-dialog .el-message-box__message {
  max-height: 400px !important; /* 设置弹窗最大高度 */
  overflow-y: auto !important; /* 当内容超出最大高度时显示垂直滚动条 */
}
</style>
